'''
日期、时间格式化工具类
    %y 两位数的年份表示（00-99）
    %Y 四位数的年份表示（000-9999）
    %m 月份（01-12）
    %d 月内中的一天（0-31）
    %H 24小时制小时数（0-23）
    %I 12小时制小时数（01-12）
    %M 分钟数（00-59）
    %S 秒（00-59）
    %a 本地简化星期名称
    %A 本地完整星期名称
    %b 本地简化的月份名称
    %B 本地完整的月份名称
    %c 本地相应的日期表示和时间表示
    %j 年内的一天（001-366）
    %p 本地A.M.或P.M.的等价符
    %U 一年中的星期数（00-53）星期天为星期的开始
    %w 星期（0-6），星期天为星期的开始
    %W 一年中的星期数（00-53）星期一为星期的开始
    %x 本地相应的日期表示
    %X 本地相应的时间表示
    %Z 当前时区的名称
    %% %号本身

--------------------------------------pandas date_range freq 参数的详细描述-----------------------------
pd.date_range(start='2018-1-1',periods=10,freq='s')

B business day frequency 工作日频率
C custom business day frequency 自定义工作日频率
D calendar day frequency 日历日频率
W weekly frequency 每周频率
M month end frequency 月末频率
SM semi-month end frequency (15th and end of month) 半月结束频率（15日和月末）
BM business month end frequency 营业月结束频率
CBM custom business month end frequency 自定义营业月结束频率
MS month start frequency 月开始频率
SMS semi-month start frequency (1st and 15th) 半月开始频率（第1天和第15天）
BMS business month start frequency 营业月开始频率
CBMS custom business month start frequency 自定义营业月开始频率
Q quarter end frequency 四分之一结束频率
BQ business quarter end frequency 业务季度结束频率
QS quarter start frequency 季度开始频率
BQS business quarter start frequency 业务季开始频率
A, Y year end frequency 年终频率
BA, BY business year end frequency 业务年度结束频率
AS, YS year start frequency 年开始频率
BAS, BYS business year start frequency 营业年度开始频率
BH business hour frequency 营业时间频率
H hourly frequency 每小时频率
T, min minutely frequency 分钟的频率
S secondly frequency 秒钟的频率
L, ms milliseconds 毫秒
U, us microseconds 微妙
N nanoseconds 纳秒
'''
import datetime
import locale
import time
import traceback
from datetime import timedelta

locale.setlocale(locale.LC_ALL, 'en')
locale.setlocale(locale.LC_CTYPE, 'chinese')

DATETIME_FORMART_TYPE = {
    'yyyy-mm-hh HH:MM:SS': '%Y-%m-%d %H:%M:%S'
}

'''
将字符串时间转换成时间对象
timeStr = "2021-04-06 16:16:14"
t = parseDateTimeBy(timeStr, "%Y-%m-%d %H:%M:%S")
'''


def parseDateTimeBy(timeStr, formart):
    return time.strptime(timeStr, formart)


'''
将时间对象格式化输出
formatDateTimeBy(t, "%Y%m%d%H%M%S")
'''


def formatDateTimeBy(t, formart):
    try:
        date = time.strftime(formart, t)
        return date
    except Exception as ex:
        print(t, formart)
        print(ex)
        return ''


'''
获取当前时间戳
'''


def getCurTimeStamp():
    ticks = time.time()
    return ticks


'''
获取当前时间
返回本地时间为 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)
'''


def getCurTime():
    localtime = time.localtime(time.time())
    return localtime


'''
将time.struct_time结构格式化成时间戳
'''


def formatTimeStamp(timeStruct):
    return time.mktime(timeStruct)


'''
返回day天前的当前时间
'''


def getPreTime(day):
    t = (datetime.datetime.now() + datetime.timedelta(days=day)).strftime("%Y-%m-%d %H:%M:%S")
    # print(t)
    return t


'''
返回当前时间的小时数
'''


def getCurTimeHour():
    t = datetime.datetime.now()
    return t.hour


'''
返回当前日期day天前的时间
%Y-%m-%d
'''


def get_pretime_by_format(day, format):
    t = (datetime.datetime.now() + datetime.timedelta(days=day)).strftime(format)
    # print(t)
    return t


'''
返回指定日期day天前的时间
date_str = 2022-03-01
%Y-%m-%d
'''


def get_pretime_by_date_str(date_str, day, format):
    start_time = datetime.datetime.strptime(date_str, format)
    t = (start_time + datetime.timedelta(days=day)).strftime(format)
    # print(t)
    return t


'''
返回指定日期day天前的时间戳
date_str = 2022-03-01
%Y-%m-%d
'''


def get_pretimestamp_by_date_str(date_str, day, format):
    start_time = datetime.datetime.strptime(date_str, format)
    t = (start_time + datetime.timedelta(days=day)).timestamp()
    # print(t)
    return t


'''
返回指定日期day天前的时间
date_str = 2022-03-01
%Y-%m-%d
'''


def get_pretime_by_date_str1(date_str, day, in_format, out_format):
    start_time = datetime.datetime.strptime(date_str, in_format)
    t = (start_time + datetime.timedelta(days=day)).strftime(out_format)
    # print(t)
    return t


'''
返回两个时间之间相差的天数
start_date = '2022-03-01 00:00:00'
end_date = '2022-03-02 00:00:00'
'''


def get_time_difference(start_time_str, end_time_str):
    start_time = datetime.datetime.strptime(start_time_str, "%Y-%m-%d %H:%M:%S")
    end_time = datetime.datetime.strptime(end_time_str, "%Y-%m-%d %H:%M:%S")
    s_timedelta = end_time - start_time
    return s_timedelta.days


'''
返回与当前时间差
'''


def get_curtime_difference(start_time_str, format):
    start_time = datetime.datetime.strptime(start_time_str, format)
    end_time = datetime.datetime.now()
    s_timedelta = end_time - start_time
    return s_timedelta.seconds


'''

'''


def get_time_difference_by_format(start_time_str, end_time_str, format):
    start_time = datetime.datetime.strptime(start_time_str, format)
    end_time = datetime.datetime.strptime(end_time_str, format)
    s_timedelta = end_time - start_time
    return s_timedelta.days


'''
返回start_time_str, end_time_str之间的日期数组
start_time_str = %Y-%m-%d
end_time_str = %Y-%m-%d
'''


def get_date_str_list_by_date_range(start_time_str, end_time_str, format):
    days = get_time_difference_by_format(start_time_str, end_time_str, format)
    date_str_list = []
    for i in range(days + 1):
        date_str_list.append(get_pretime_by_date_str(start_time_str, i, format))
    return date_str_list


'''
返回start_time_str, end_time_str之间的日期时间戳数组
start_time_str = %Y-%m-%d
end_time_str = %Y-%m-%d
'''


def get_datestamp_str_list_by_date_range(start_time_str, end_time_str, format):
    days = get_time_difference_by_format(start_time_str, end_time_str, format)
    date_str_list = []
    for i in range(days + 1):
        date_str_list.append(get_pretimestamp_by_date_str(start_time_str, i, format))
    return date_str_list


'''
返回指定月份的开时日期和结束日期
'''


def get_startdate_and_enddate_by_month(start_month):
    start_month_time = time.strptime(start_month, '%Y-%m')
    # print(type(start_month_time))
    # print(start_month_time)
    # print("start_month={}".format(start_month))

    # 下月第一天最后一秒时间
    month = start_month_time.tm_mon
    year = start_month_time.tm_year
    if month == 12:
        month = 0
        year = year + 1

    future_mouth_first_daytime = datetime.datetime(year, month + 1, 1, 0, 0, 0)
    # print("future_mouth_first={}".format(future_mouth_first_daytime))
    # 当月最后一天最后一秒时间
    this_month_last_daytime = future_mouth_first_daytime - datetime.timedelta(days=1)
    # print(type(this_month_last_daytime))
    # print(this_month_last_daytime)
    # 当月第一点最后一秒
    this_month_first_daytime = datetime.datetime(start_month_time.tm_year, start_month_time.tm_mon, 1, 0, 0, 0)
    # print(type(this_month_first_daytime))
    # print(this_month_first_daytime)
    # print("this_month_last_daytime={}".format(this_month_last_daytime))
    # print("this_month_first_daytime={}".format(this_month_first_daytime))

    start_time = this_month_first_daytime.strftime('%Y-%m-%d')
    end_time = this_month_last_daytime.strftime('%Y-%m-%d')
    # print("start_time={}".format(start_time))
    # print("end_time={}".format(end_time))
    return start_time, end_time


'''
年月日转年积日
'''


def date2doy(year, month, day):
    month_leapyear = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    month_notleap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    doy = 0

    if month == 1:
        pass
    elif year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        for i in range(month - 1):
            doy += month_leapyear[i]
    else:
        for i in range(month - 1):
            doy += month_notleap[i]
    doy += day
    return doy


def get_weekday():
    today = datetime.datetime.now()
    # 取今天日期以及星期等信息
    date = today.day
    # 取今天日期
    month = today.month
    # 取今天月份
    year = today.year
    # 取年份
    weekday = datetime.datetime.isoweekday(today)
    print('weekday = {}'.format(weekday))


'''
获取指定日期所有的周的开始日期和结束日期
'''


def get_week_range(date):
    year, week, dow = date.isocalendar()
    # Find the first day of the week.
    if dow == 7:
        # Since we want to start with Sunday, let's test for that condition.
        start_date = date
    else:
        # Otherwise, subtract `dow` number days to get the first day
        start_date = date - timedelta(dow)

    # Now, add 6 for the last day of the week (i.e., count up to Saturday)
    end_date = start_date + timedelta(6)

    return (start_date, end_date)


'''
返回pre_date相对于当前日期的天数
'''


def get_days_beteen_predate_and_curdate(pre_date_str):
    start_time = datetime.datetime.strptime(pre_date_str, "%Y-%m-%d")
    cur_date = datetime.datetime.now()
    s_timedelta = cur_date - start_time
    return s_timedelta.days


'''
比较pre_date_time与当前时间的差值(秒)
'''


def compate_time(pre_date_time, cur_date_time=''):
    try:
        if not cur_date_time:
            cur_date_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        pre_dt = datetime.datetime.strptime(pre_date_time, '%Y-%m-%d %H:%M:%S')
        cur_dt = datetime.datetime.strptime(cur_date_time, '%Y-%m-%d %H:%M:%S')
        pre_dt_stamp = time.mktime(pre_dt.timetuple())
        cur_dt_stamp = time.mktime(cur_dt.timetuple())
    except:
        print(traceback.format_exc())
        return 99999.
    diff = cur_dt_stamp - pre_dt_stamp
    return diff


'''
返回day天前的当前时间
'''


def getPreTimeByFormat(day, t_format):
    t = (datetime.datetime.now() + datetime.timedelta(days=day)).strftime(t_format)
    # print(t)
    return t


'''
返回当前时间的小时数
'''


def get_cur_daytime_by_hours():
    localtime = time.localtime(time.time())
    return localtime.tm_hour


if __name__ == '__main__':
    # timeStr = "2021-04-06 16:16:14"
    # t = parseDateTimeBy(timeStr, "%Y-%m-%d %H:%M:%S")
    # print(type(t))
    # print(formatDateTimeBy(t, "%Y%m%d%H%M%S"))
    # print(formatDateTimeBy(parseDateTimeBy(timeStr, "%Y-%m-%d %H:%M:%S"), "%Y%m%d%H%M%S"))

    # print(time.mktime(parseDateTimeBy(timeStr, "%Y-%m-%d %H:%M:%S")))
    # print(getPreTime(-1))
    # print(formatDateTimeBy(getCurTime(), "%Y-%m-%d %H:%M:%S"))
    # print(date2doy(2021, 9, 20))
    # print(int(time.time()*1000))

    # start_date = "2022-07-15"
    # end_date = '2022-08-02'
    # print(get_date_str_list_by_date_range(start_date, end_date, "%Y-%m-%d"))
    # get_time_difference(start_date, end_date)
    # get_weekday()
    # today = datetime.datetime.now()
    # #print(get_week_range(today))
    #
    # now_str = get_pretime_by_format(0, '%Y-%m-%d')
    # pre_7_str = get_pretime_by_format(-7, '%Y-%m-%d')
    #
    # print('now_str = {}, pre_7_str = {}'.format(now_str, pre_7_str))
    #
    # start_date_str = '2022-03-01 00:00:00'
    # print(get_pretime_by_date_str(start_date_str, -7, '%Y-%m-%d'))

    # print(get_date_str_list_by_date_range('2022-03-01', '2022-03-10', '%Y-%m-%d'))

    # print(get_days_beteen_predate_and_curdate('2022-04-14'))

    # print((get_startdate_and_enddate_by_month('2022-04')))

    # print(get_pretime_by_format(-3650, '%Y-%m-%d'))

    # print(getCurTimeHour())
    cts = "20220919141620"
    print(get_curtime_difference(cts, "%Y%m%d%H%M%S"))
